﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace lipesin.Main.Category
{
	public partial class CategoryEditor : Form
	{
		DataTable _category;
		long? _id = null;
		public CategoryEditor()
		{
			InitializeComponent();
		}
		
		/// <summary>
		/// Редактирование категории
		/// </summary>
		/// <param name="owner"></param>
		/// <param name="type"></param>
		/// <param name="parentId">-1 для удаления категории</param>
		/// <param name="categoryId">null для создания новой категории</param>
		/// <returns></returns>
		public long? EditCategory(IWin32Window owner, CategoryType type, long? parentId, long? categoryId)
		{
			if (!categoryId.HasValue) categoryId = 0;
			_category = Dalc.ExecuteToDataTable("select * from category where id = {0}".F(categoryId));
			DataRow category;
			if (_category.Rows.Count == 0)
			{
				category = _category.NewRow();
				_category.Rows.Add(category);
				category["parent_id"] = parentId ?? (object)DBNull.Value;
				category["type"] = parentId.HasValue ? (object)DBNull.Value : (int)type;
				string maxOrderSelect = null;
				if (parentId.HasValue)
					maxOrderSelect = "select max([order]) + 1 from category where parent_id = {0}".F(parentId);
				else
					maxOrderSelect = "select max([order]) + 1 from category where type = {0}".F((int)type);
				category["order"] = Dalc.ExecuteToScalar(maxOrderSelect);
				category["date_from"] = DateTime.Today;
				this.Text = "Добавить категорию";
				btnOk.Text = "Добавить";
			}
			else if (parentId == -1)
			{
				this.Text = "Удалить категорию";
				btnOk.Text = "Удалить";
				category = _category.Rows[0];
				category["date_to"] = DateTime.Today;
				ctlName.ReadOnly = true;
				ctlDateFrom.ReadOnly = true;
				ctlDateTo.ReadOnly = true;
			}
			category = _category.Rows[0];
			ctlName.Value = category["name"];
			ctlDateFrom.Value = category["date_from"];
			ctlDateTo.Value = category["date_to"];
			this.ShowDialog(owner);
			return _id;
		}

		private void btnOk_Click(object sender, EventArgs e)
		{
			DataRow category = _category.Rows[0];
			if (Convert.IsDBNull(category["id"]))
				category["id"] = Dalc.NextId();
			_id = (long)category["id"];
			category["name"] = ctlName.Value;
			category["date_from"] = ctlDateFrom.Value;
			category["date_to"] = ctlDateTo.Value??DBNull.Value;
			Dalc.UpdateDataTable(_category);
			this.Close();
		}
	}
}
